package com.neuedu.his.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.neuedu.his.mapper.*;
import com.neuedu.his.po.*;
import com.neuedu.his.service.MedicalrecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Service
public class MedicalrecordServiceImpl extends ServiceImpl<MedicalrecordMapper, Medicalrecord> implements MedicalrecordService {

    @Autowired
    private MedicalrecordMapper medicalRecordMapper;

    @Autowired
    private MedicaldiseaseMapper medicalDiseaseMapper;

    @Autowired
    private RegisterMapper registerMapper;

    @Autowired
    private DiseaseMapper diseaseMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> saveMedicalRecord(Medicalrecord medicalRecord, List<Medicaldisease> diagnoses, String action, Integer doctorId) {
        Map<String, Object> result = new HashMap<>();

        try {
            // 验证诊断信息
            if (diagnoses == null || diagnoses.isEmpty()) {
                throw new IllegalArgumentException("至少需要添加一个诊断");
            }

            // 验证疾病是否存在
            for (Medicaldisease diagnosis : diagnoses) {
                Disease disease = diseaseMapper.selectById(diagnosis.getDiseaseid());
                if (disease == null) {
                    throw new IllegalArgumentException("疾病ID " + diagnosis.getDiseaseid() + " 不存在");
                }
            }

            // 获取挂号记录并验证
            Register register = registerMapper.selectById(medicalRecord.getRegistid());
            if (register == null) {
                throw new IllegalArgumentException("挂号记录不存在");
            }

            if (!Objects.equals(register.getUserid(), doctorId)) {
                throw new IllegalArgumentException("无权操作该患者的病历");
            }

            // 检查是否已存在病历
            Medicalrecord existingRecord = getByRegistId(medicalRecord.getRegistid());
            boolean isUpdate = existingRecord != null;

            if (isUpdate) {
                // 如果已提交，不允许修改
                if (existingRecord.getCasestate() != null && existingRecord.getCasestate() == 2) {
                    throw new IllegalArgumentException("病历已提交，无法修改");
                }
                medicalRecord.setId(existingRecord.getId());
            }

            // 设置病历状态
            if ("save".equalsIgnoreCase(action)) {
                medicalRecord.setCasestate(1); // 暂存
            } else if ("submit".equalsIgnoreCase(action)) {
                medicalRecord.setCasestate(2); // 已提交
                // 更新挂号状态为就诊中
                register.setVisitstate(2);
                registerMapper.updateById(register);
            } else {
                throw new IllegalArgumentException("无效的操作类型");
            }

            // 保存或更新病历
            boolean success;
            if (isUpdate) {
                success = medicalRecordMapper.updateById(medicalRecord) > 0;
            } else {
                medicalRecord.setCasenumber(register.getCasenumber());
                success = medicalRecordMapper.insert(medicalRecord) > 0;
            }

            if (!success) {
                throw new RuntimeException("保存病历失败");
            }

            // 先删除原有诊断
            if (isUpdate) {
                medicalDiseaseMapper.deleteByMedicalId(medicalRecord.getId());
            }

            // 再新增诊断
            for (Medicaldisease diagnosis : diagnoses) {
                diagnosis.setMedicalid(medicalRecord.getId());
                diagnosis.setRegistid(medicalRecord.getRegistid());
                if (diagnosis.getDiagnosecate() == null) {
                    diagnosis.setDiagnosecate(1); // 默认初诊
                }
                if (diagnosis.getDiagnosetype() == null) {
                    diagnosis.setDiagnosetype(1); // 默认西医
                }
                medicalDiseaseMapper.insert(diagnosis);
            }

            result.put("success", true);
            result.put("message", "save".equalsIgnoreCase(action) ? "暂存成功" : "提交成功");
            result.put("medicalRecordId", medicalRecord.getId());

        } catch (Exception e) {
            result.put("success", false);
            result.put("message", e.getMessage());
        }

        return result;
    }

    @Override
    public Medicalrecord getByRegistId(Integer registId) {
        return medicalRecordMapper.selectOne(new QueryWrapper<Medicalrecord>()
                .eq("RegistID", registId));
    }

    @Override
    public List<Medicaldisease> getDiagnosesByMedicalId(Integer medicalId) {
        return medicalDiseaseMapper.selectList(new QueryWrapper<Medicaldisease>()
                .eq("MedicalID", medicalId));
    }

    @Override
    public Map<String, Object> getMedicalRecordWithDiagnoses(Integer registId, Integer doctorId) {
        Map<String, Object> result = new HashMap<>();

        // 验证挂号记录
        Register register = registerMapper.selectById(registId);
        if (register == null) {
            throw new IllegalArgumentException("挂号记录不存在");
        }

        if (!Objects.equals(register.getUserid(), doctorId)) {
            throw new IllegalArgumentException("无权查看该患者的病历");
        }

        Medicalrecord record = getByRegistId(registId);
        List<Medicaldisease> diagnoses = null;

        if (record != null) {
            diagnoses = getDiagnosesByMedicalId(record.getId());
        }

        result.put("medicalRecord", record);
        result.put("diagnoses", diagnoses);
        result.put("success", true);

        return result;
    }
}